package main

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/nsqio/go-nsq"
	"go-web/model"
	"io"
	"log"
	"math/rand"
	"os"
	"time"
)

var mq *nsq.Producer
func main() {

	conn := "39.100.58.10:4150"
	config := nsq.NewConfig()
	var err error
	mq, err = nsq.NewProducer(conn, config)
	if err != nil {
		log.Panic(err)
	}

	rand.Seed(time.Now().UnixNano())

	gin.SetMode(gin.ReleaseMode)
	f, _ := os.Create("gin.log")
	gin.DefaultWriter = io.MultiWriter(f)

	r := gin.Default()
	r.GET("/send1", func(c *gin.Context) {
		send()
		c.JSON(200, gin.H{
			"times": 1,
		})
	})

	r.GET("/send2", func(c *gin.Context) {
		send()
		send()
		c.JSON(200, gin.H{
			"times": 2,
		})
	})


	r.Run()
}

func send() {
	var orderMsg = new(model.OrderMsg)
	orderMsg.OrderId = 1
	orderMsg.GoodsId = 1
	orderMsg.Number = 1
	orderMsg.UserId = 1
	orderMsg.CreatedAt = time.Now()

	jsonBytes, err := json.Marshal(orderMsg)
	if err != nil {
		log.Fatal(err)
	}

	// 发消息
	err = mq.Publish("order", jsonBytes)
	if err != nil {
		log.Panic(err)
	}
}
